const {comMysql} = require("../db/mysql")
const fs = require("fs")

const addPDF = (req,res)=>{
    let {name,type,pdf,username,size,direction} = req.body
    let sql = `insert into pdf(name,type,pdf,time,uploadNum,seeNum,size,direction,username) values (?,?,?,?,?,?,?,?,?)`
    let time = new Date().getTime()+''
    let uploadNum = 0
    let seeNum = 0
    let arr = [name,type,pdf,time,uploadNum,seeNum,size,direction,username]
    console.log(name,type,pdf,username,size,direction)
    return comMysql(sql,arr)
}
const deletePDF = async (req,res)=>{
    let {id,username} = req.body
    let sql = `delete from pdf where id = ? and username = ?`
    let arr = [id,username]
    let data = await searchPDFfromId(req,res)
    if(data.length>0&&data[0].pdf){
        let num = data[0].pdf.indexOf("?")      
        let next1=data[0].pdf.substring(num)
        let next2=next1.split("&")[0].split("=")[1]
        let next3 = "./"+next2
        if(fs.existsSync(next3)){
          fs.unlink(next3,(err)=>{
            if(!err){
              console.log("删除成功");
            }else{
              console.log("删除失败");
            }
          })
        }
      }
    return comMysql(sql,arr)
}
const PDF = (req,res)=>{
  let {pdf,username} = req.query
  pdf = "http://localhost:3001/api/upload/PDF?pdf="+pdf+"&username="+username
  let sql = "select * from users where username = ? and pdf = ?"
  let arr = [username,pdf]
  return comMysql(sql,arr)
}
const searchPDFfromId = (req,res)=>{
    let {id} = req.query
    let sql = `select * from pdf where id = ?`
    let arr = [id]
    return comMysql(sql,arr)
}

const searchPDF = (req,res)=>{
    let sql = `select * from pdf order by type,direction desc`
    return comMysql(sql)
}
const updatePDF = (req,res)=>{
    let {name,type,id} = req.body
    let sql = `update pdf set name = ? and type = ? where id = ?`
    let arr = [name,type,id]
    return comMysql(sql,arr)
}
const updatePDFGoodNum = (req,res,Num)=>{
  let {id} = req.query
  
  let {uploadNum,seeNum} = Num
  seeNum+=1
  let sql = `update pdf set seeNum = ? where id = ?`
  let arr = [seeNum,id]
  return comMysql(sql,arr)
}
const updatePDFuploadNum = (req,res,Num)=>{
  let {id} = req.query
  
  let {uploadNum,seeNum} = Num
  
  uploadNum+=1
  let sql = `update pdf set uploadNum = ? where id = ?`
  let arr = [uploadNum,id]
  return comMysql(sql,arr)
}
module.exports = {
    addPDF,
    deletePDF,
    searchPDF,
    updatePDF,
    PDF,
    updatePDFGoodNum,
    searchPDFfromId,
    updatePDFuploadNum
}